package org.example.thread;


import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @Description 通用线程池
 * @Author feixiang.li
 * @Date 2024/12/17 10:09
 */
public class TaskThreadPool {
    private static ExecutorService execute = init();
    private static ScheduledExecutorService scheduledThreadPool = new ScheduledThreadPoolExecutor(6);


    private static ExecutorService init() {
        // 核心线程数
        int corePoolSize = 4;
        // 最大线程数
        int maximumPoolSize = 10;
        // 线程空闲存活时间
        long keepAliveTime = 60L;
        // 任务队列
        BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>(100);
        return new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                TimeUnit.SECONDS,
                workQueue,
                new ThreadPoolExecutor.CallerRunsPolicy()
        );
    }

    public static Future<Object> submit(Callable<Object> handler) {
        return execute.submit(handler);
    }

    public static Boolean execute(Runnable runnable) {
        execute.execute(runnable);
        return true;
    }

    public static void schedule(Callable callable, Integer delay) {
        scheduledThreadPool.schedule(callable, delay, TimeUnit.MINUTES);
    }

}
